package poketrade.managers;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import poketrade.entities.Carte;
import poketrade.entities.PendingOffer;
import poketrade.entities.User;

@Stateless
public class DealManager {

	@PersistenceContext(name="Poketrade")
	EntityManager em;
	
	public User publishOffer(long user_offerer, String cardIdentifier, float basePrice)
	{
		User currentUser = em.find(User.class, user_offerer);
		if (currentUser == null)
			return null;
		
		Carte carte = em.find(Carte.class, cardIdentifier);
		if (carte == null)
			return null;
		
		PendingOffer offer = new PendingOffer();
		offer.setOffer(carte);
		offer.setOfferer(currentUser);
		offer.setBasePrice(basePrice);
		
		currentUser.addOffer(offer);
		
		em.persist(offer);
		
		return currentUser;
	}
	
	public User fetchPendingOffersForUser(User u)
	{
		User user = em.find(User.class, u.getId());
		// Force a fetch.
		user.getOffers().size();
		return user;
	}
	
	public User concludeDeal(long pendingOffer, long user_buyer)
	{
		User buyer = em.find(User.class, user_buyer);
		if (buyer == null)
			return null;
		PendingOffer offer = em.find(PendingOffer.class, pendingOffer);
		if (offer == null || offer.isConcluded())
			return null;
		User offerer = offer.getOfferer();
		
		float finalPrice = offer.getBasePrice();
		if (!buyer.getPremium())
			finalPrice *= 1.1;
		if (!offerer.getPremium())
			finalPrice *= 1.1;
		
		if (buyer.getSolde() >= finalPrice)
		{
			buyer.setSolde(buyer.getSolde() - finalPrice);
			offerer.setSolde(offerer.getSolde() + offer.getBasePrice());
			
			offer.setBuyer(buyer);
			return buyer;
		}
		else
			return null;
		
	}
	
	@SuppressWarnings("unchecked")
	public List<PendingOffer> getOffers()
	{
		return em.createNamedQuery("getAllOffers").getResultList();
	}
	
	public PendingOffer getOffer(long id)
	{
		return em.find(PendingOffer.class, id);
	}
	
	public void removeOffer(long pendingOffer)
	{
		em.remove(em.find(PendingOffer.class, pendingOffer));
	}

	public List<PendingOffer> getNonConcludedOffers() {
		List<PendingOffer> l = getOffers();
		List<PendingOffer> ret = new ArrayList<PendingOffer>();
		for (PendingOffer o : l)
			if (!o.isConcluded())
				ret.add(o);
		return ret;
	}
}
